<template>
    <div class="app-container">
        <!-- 添加或修改项目基础信息管理对话框 -->
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="98px">
            <el-form-item label="生产单号" prop="produceNo">
                <el-input v-model="queryParams.produceNo" placeholder="请输入生产单号" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="工程名称" prop="gongchengName">
                <el-input v-model="queryParams.gongchengName" placeholder="请输入工程名称" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>

            <el-form-item label="工序名称" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入工序名称" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="产品名称" prop="goodsName">
                <el-input v-model="queryParams.goodsName" placeholder="请输入产品名称" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>

            <el-form-item label="产品型号" prop="goodModel">
                <el-input v-model="queryParams.goodModel" placeholder="请输入产品型号" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="图纸号" prop="shuoming">
                <el-input v-model="queryParams.shuoming" placeholder="请输入图纸号" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="生产产品名称" prop="gongxuName">
                <el-input v-model="queryParams.gongxuName" placeholder="请输入生产产品名称" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>

            <el-form-item label="生产产品型号" prop="gongxuModel">
                <el-input v-model="queryParams.gongxuModel" placeholder="请输入生产产品型号" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="车间" prop="deptName">
                <el-select v-model="queryParams.deptName" placeholder="请选择车间" style="width: 100%"
                    @change="handshopChange" clearable>
                    <el-option v-for="(item, index) in workshopOptions" :key="index" :label="item.label"
                        :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="分配人" prop="updateBy">
                <el-input v-model="queryParams.updateBy" placeholder="请输分配人" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="任务分配状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="任务分配状态" clearable style="width: 130px">
                    <el-option v-for="dict in dict.type.task_status" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="multiple"
                @click="piliangPaigong()" v-hasPermi="['develop:PaichanTask:piliangBnt']">批量计件派工</el-button>
            <el-button type="info" plain icon="el-icon-edit" size="mini" :disabled="multiple"
                @click="piliangPaigongJishi()" v-hasPermi="['develop:PaichanTask:piliangBnt']">批量计时派工</el-button>
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="paigongZahuo()"
                v-hasPermi="['develop:PaichanTask:piliangBnt']">杂活计件派工</el-button>
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="paigongJishiZahuo()"
                v-hasPermi="['develop:PaichanTask:piliangBnt']">杂活计时派工</el-button>
            <el-button icon="el-icon-edit" size="mini" @click="batchModifyGongxu">批量修改工序</el-button>
        </el-col>

        <el-table :data="columns" ref="dragTable" row-key="id" v-loading="loading"
            @selection-change="handleSelectionChange" @sort-change="handleSortChange" show-summary
            :summary-method="getSummaries">
            <el-table-column align="center" type="selection" width="55" />
            <el-table-column align="center" label="序号" type="index" width="50">
                <template slot-scope="scope">
                    <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column sortable label="生产单号" align="center" prop="produceNo" />
            <!--   <el-table-column sortable label="订单编号" align="center" prop="projectNo" show-overflow-tooltip />-->
            <el-table-column label="工程名称" align="center" prop="gongchengName" />
            <!--<el-table-column align="center" label="合同交货日期"  prop="deliveryTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deliveryTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>-->
            <el-table-column sortable label="产品编码" align="center" prop="goodsCode" />
            <!-- <el-table-column sortable label="任务分配状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.task_status" :value="scope.row.status" />
        </template>
      </el-table-column>-->
            <el-table-column sortable align="center" label="产品名称" prop="goodsName" show-overflow-tooltip />
            <el-table-column sortable align="center" label="产品型号" prop="goodModel" />
            <el-table-column sortable align="center" label="工序名称" prop="name">
                <template slot-scope="scope">
                    <el-tooltip class="item" content="点击查看详情" effect="dark" placement="left-start">
                        <span @click="showDetailGongxuUser(scope.row)" style="color: #00afff;cursor:pointer;">
                            {{ scope.row.name }}</span>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column sortable align="center" label="是否最后一道工序" prop="islast">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.yes_no" :value="scope.row.islast" />
                </template>
            </el-table-column>
            <el-table-column sortable align="center" label="分配人" prop="updateBy" />
            <el-table-column align="center" label="车间" prop="deptName" show-overflow-tooltip />
            <el-table-column align="center" label="标准工时" prop="workHour" show-overflow-tooltip />
            <el-table-column sortable label="生产产品名称" align="center" prop="gongxuName" />
            <el-table-column sortable label="生产产品型号" align="center" prop="gongxuModel" />
            <el-table-column sortable label="单价" align="center" prop="money" />
            <el-table-column sortable label="总数量" align="center" prop="counts" />
            <el-table-column sortable label="已分配数量" align="center" prop="fenpeiCount" />
            <!-- <el-table-column sortable label="剩余分配数量" align="center" prop="remainCount" />-->
            <el-table-column sortable label="已完成数量" align="center" prop="finishCount" />
            <el-table-column sortable label="剩余完成数量" align="center" prop="remainfinishCount" />
            <el-table-column align="center" label="图纸号" prop="shuoming" show-overflow-tooltip />
            <el-table-column align="center" label="产品备注" prop="remark" show-overflow-tooltip />
            <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
                <template slot-scope="scope">
                    <el-button @click="modifyMoney(scope.row)" icon="el-icon-view" size="mini" type="text"
                        v-hasPermi="['develop:PaichanTask:editBnt']">
                        修改单价
                    </el-button>
                    <el-popconfirm :title="`确认要删除该工序吗？`" @confirm="deleteGx(scope.row)" style="margin-left: 10px;">
                        <el-button slot="reference" size="mini" type="text" icon="el-icon-close">
                            删除工序
                        </el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <goods-sale-do-gongxu-form-all @ok="getList" ref="batchModifyGongxuForm"></goods-sale-do-gongxu-form-all>
        <taskModify-form @ok="getList" ref="taskModifyForm"></taskModify-form>
        <piliangPaigong-form @ok="getList" ref="piliangPaigongForm"></piliangPaigong-form>
        <piliangPaigongJishi-form @ok="getList" ref="piliangPaigongJishiForm"></piliangPaigongJishi-form>
        <paigongZahuo-form @ok="getList" ref="paigongZahuoForm"></paigongZahuo-form>
        <paigongJishiZahuo-form @ok="getList" ref="paigongJishiZahuoForm"></paigongJishiZahuo-form>
        <piliangPaigong-form @ok="getList" ref="piliangPaigongForm"></piliangPaigong-form>
        <shengchanDoGongxuUser-form @ok="getList" ref="shengchanDoGongxuUserForm"></shengchanDoGongxuUser-form>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
    </div>
</template>

<script>
import GoodsSaleDoGongxuFormAll from "@/views/develop/lnGongxu/module/GoodsSaleDoGongxuFormAll.vue";
import TaskModifyForm from "@/views/develop/projectBaseInfo/prjForGoodsIn/TaskModifyForm";
import { addAction, deleteAction, downloadFile, getAction, getById, accAdd } from '@/api/manage'
import PiliangPaigongForm from "@/views/develop/projectBaseInfo/prjForGoodsIn/PiliangPaigongForm";
import PiliangPaigongJishiForm from "@/views/develop/projectBaseInfo/prjForGoodsIn/PiliangPaigongJishiForm";
import PaigongZahuoForm from "@/views/develop/projectBaseInfo/prjForGoodsIn/PaigongZahuoForm";
import PaigongJishiZahuoForm from "@/views/develop/projectBaseInfo/prjForGoodsIn/PaigongJishiZahuoForm";
import ShengchanDoGongxuUserForm from '@/views/develop/goodsSale/module/ShengchanDoGongxuUserForm.vue';
export default {
    name: "PaichanTaskYifenpeiList",
    dicts: ['isdo', 'task_status', 'yes_no'],
    components: {
        PiliangPaigongForm,
        TaskModifyForm,
        PiliangPaigongForm,
        PiliangPaigongJishiForm,
        PaigongZahuoForm,
        PaigongJishiZahuoForm,
        GoodsSaleDoGongxuFormAll,
        ShengchanDoGongxuUserForm,
    },
    props: {
        projectCode: {
            type: [String],
            required: true,
            default: ''
        },
    },
    data() {
        return {
            // 遮罩层
            loading: true,
            activeName: "first",
            // 弹出层标题
            title: "已排产任务",
            // 是否显示弹出层
            open: false,
            single: true,
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 表单参数
            form: {},
            proId: "",
            proStatus: "",
            columns: [],
            selectRows: [],
            total: 0,
            // 表单校验
            rules: {},
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                params: {},
                id: null,
                code: null,
                name: null,
                shuoming: null,
                produceNo: null,
                projectNo: null,
                gongchengName: null,
                goodsName: null,
                goodsCode: null,
                goodModel: null,
                gongxuName: null,
                gongxuModel: null,
                model: null,
                brand: null,
                //isdo: "1",
                status: "1",
                remark: null,
                projectId: null,
                updateBy: null,
                //deptId: this.$store.getters.deptId,
                deptName: this.$store.getters.deptName,
                orderByColumn: "create_time",
                isAsc: "desc",
            },
            url: {
                list: '/goodsSaledoGongxu/goodsSaledoGongxu/listSaleProFinish',
                getById: '/projectBaseInfo/projectBaseInfo/',
                exportData: '/goodsSale/goodsSale/exportData',
                userTreeSelect: '/system/dept/userTreeSelect',
                deleteGx: '/goodsSaledoGongxu/goodsSaledoGongxu/remove/',
            },
            workshopOptions: [

            ],
            tableMaxHeight: window.innerHeight - 320,
        };
    },
    watch: {
        'projectCode': {
            handler(newVal, oldVal) {
                console.log("projectCode", newVal);
                if (newVal) {
                    this.queryParams.projectNo = newVal;
                    this.getList();
                }
            },
            deep: true,
            immediate: true
        },
    },
    created() {
        //this.handleQuery();
        this.getList();
        this.getUser();
        window.addEventListener('resize', this.getTableHeight);
    },
    methods: {
        showDetailGongxuUser(row) {
            this.$refs.shengchanDoGongxuUserForm.show(row);
        },
        deleteGx(row) {
            const ids = row.id;
            deleteAction(this.url.deleteGx, ids).then(response => {
                this.getList();
                this.$modal.msgSuccess("删除成功！");
            }).catch(() => {
            });
        },
        handshopChange(e) {
            // 查找匹配的选项，不仅匹配value，也匹配id
            const selected = this.workshopOptions.find(item => item.value === e || item.id === e);
            if (selected) {
                // 设置表单的部门ID和名称
                // this.queryParams.deptId = selected.id;
                this.queryParams.deptName = selected.label;
            }
        },
        getUser() {
            let that = this;
            getAction(that.url.userTreeSelect, { parentId: '57d779853f0f4d14b03d51db30099456' }).then(res => {
                that.workshopOptions = res.data;
            })
        },
        piliangPaigong() {
            this.$refs.piliangPaigongForm.piliangFenpeiGxpShow(this.selectRows);
        },
        piliangPaigongJishi() {
            this.$refs.piliangPaigongJishiForm.piliangFenpeiGxpShow(this.selectRows);
        },

        paigongZahuo() {
            this.$refs.paigongZahuoForm.paigongZahuoShow();
        },
        paigongJishiZahuo() {
            this.$refs.paigongJishiZahuoForm.paigongJishiZahuoShow();
        },
        getSummaries(param) {
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = "合计";
                    return;
                }
                const values = data.map((item) => Number(item[column.property]));
                // 只合计amount1和amount3，想合并哪些列就在这里指定
                if (column.property === "counts" || column.property === "finishCount" || column.property === "remainCount" || column.property === "remainfinishCount" || column.property === "fenpeiCount") {
                    sums[index] = values.reduce((prev, curr) => {

                        const value = Number(curr);
                        if (!isNaN(value)) {
                            return accAdd(prev, curr);
                        } else {
                            return prev;
                        }
                    }, 0);
                }
            });
            return sums;
        },
        modifyMoney(row) {
            this.$refs.taskModifyForm.modifyShow(row);
        },
        // piliangPaigong() {
        //   this.$refs.piliangPaigongForm.piliangFenpeiGxpShow(this.selectRows);
        // },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
            this.selectRows = selection;
        },
        /** 排序触发事件 */
        handleSortChange(column, prop, order) {
            this.queryParams.orderByColumn = column.prop;
            this.queryParams.isAsc = column.order;
            this.handleQuery();
        },
        xunjian(row) {
            this.$refs.xunjianForm.xunjianShow(row);
        },
        taskFp(row) {
            this.$refs.taskFpForm.taskFpShow(row);
        },
        chaijie(row) {
            this.$refs.chaijieForm.chaijieGoods(row);
        },
        choseGy(row) {
            this.$refs.choseGxForm.choseGy(row);
        },
        getList() {
            this.loading = true;
            getAction(this.url.list, this.queryParams).then(response => {
                this.columns = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        reset() {
            this.form = {
                id: null,
                remark: null,
                delFlag: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null
            };
            this.resetForm("form");
        },

        handleExportDetail(row) {
            downloadFile(this.url.exportData, this.queryParams);
        },
        /**
     * 批量修改工序
     */
        batchModifyGongxu() {
            const ids = this.ids;
            if (ids == null || ids == '' || ids == 'undefined' || ids.length === 0) {
                this.$modal.msgError("请选择至少一条记录");
                return;
            }

            // 获取选中的行数据
            const selectedRows = this.columns.filter(row => ids.includes(row.id));

            // 检查是否有不能操作的数据
            const invalidRows = selectedRows.filter(row => row.canCount === 0);
            if (invalidRows.length > 0) {
                this.$modal.msgError("存在不可操作的数据（canCount为0），请重新选择");
                return;
            }

            // 打开批量修改工序弹窗
            this.$refs.batchModifyGongxuForm.handleUpdate(ids);
        },
    }
};
</script>
